"""
@File    ：allure_des.py
@Author  ：sarah
@Date    ：2023-07-21
@Desc    ：allure报告的描述信息，每次运行重新创建
"""

import json
import os
import platform
import pytest
import selenium.webdriver.common.bidi.cdp

from config.config import cm
from config.read_cfg import smtp_cfg


# 设置报告窗口的标题
def set_windows_title(new_title):
    """
    通过修改allure-html目录下的index.html文件，设置打开的 Allure 报告的浏览器窗口标题文案
    @param new_title:  需要更改的标题文案 【 原文案为：Allure Report 】
    @return:
    """
    report_title_filepath = os.path.join('./reports/html/index.html', "index.html")
    # 定义为只读模型，并定义名称为: f
    with open(report_title_filepath, 'r+', encoding="utf-8") as f:
        # 读取当前文件的所有内容
        all_the_lines = f.readlines()
        f.seek(0)
        f.truncate()
        # 循环遍历每一行的内容，将 "Allure Report" 全部替换为 → new_title(新文案)
        for line in all_the_lines:
            f.write(line.replace("Allure Report", new_title))
        # 关闭文件
        f.close()


def set_report_name(new_name):
    """
        通过修改allure-html目录下的widgets/summary.json, 修改Allure报告Overview的标题文案
        @param new_name:  需要更改的标题文案 【 原文案为：ALLURE REPORT 】
        @return:
        """
    title_filepath = os.path.join('./reports/html/widgets/summary.json', "widgets", "summary.json")
    # 读取summary.json中的json数据，并改写reportName
    with open(title_filepath, 'rb') as f:
        # 加载json文件中的内容给params
        params = json.load(f)
        # 修改内容
        params['reportName'] = new_name
        # 将修改后的内容保存在dict中
        new_params = params
    # 往summary.json中，覆盖写入新的json数据
    with open(title_filepath, 'w', encoding="utf-8") as f:
        json.dump(new_params, f, ensure_ascii=False, indent=4)


def set_report_env_on_results():
    """
    在json报告的目录下生成一个写入环境信息的文件：environment.properties(注意：不能放置中文，否则会出现乱码)
    """
    # 需要写入的环境信息，根据实际工程填写
    allure_env = {
        'OperatingEnvironment': 'TEST',
        'BaseUrl': f'{smtp_cfg["host"]}',
        'PythonVersion': platform.python_version(),
        'PytestVersion': pytest.__version__,
        'Platform': platform.platform(),
        'selenium': selenium.__version__,
        'Browser': 'Chrome',
    }

    allure_env_file = os.path.join(cm.dir_report_json, 'environment.properties')
    with open(allure_env_file, 'w', encoding='utf-8') as f:
        for _k, _v in allure_env.items():
            f.write(f'{_k}={_v}\n')


def set_report_executer_on_results():
    """
    在json报告的目录下生成一个写入执行人的文件：executor.json
    """
    # 需要写入的运行信息
    allure_executor = {
        "name": "张三",
        "type": "jenkins",
        "url": "http://helloqa.com",  # allure报告的地址
        "buildOrder": 3,
        "buildName": "allure-report_deploy#1",
        "buildUrl": "http://helloqa.com#1",
        "reportUrl": "http://helloqa.com#1/AllureReport",
        "reportName": "张三 Allure Report"
    }
    allure_env_file = os.path.join(cm.dir_report_json, 'executor.json')
    with open(allure_env_file, 'w', encoding='utf-8') as f:
        f.write(str(json.dumps(allure_executor, ensure_ascii=False, indent=4)))


def set_report_categories_on_results():
    """
    在json报告的目录下生成一个写入统计类型的文件：categories.json
    """
    # 需要写入的运行信息
    allure_categories = [
        {
            "name": "Ignored tests",
            "matchedStatuses": ["skipped"]
        },
        {
            "name": "Infrastructure problems",
            "matchedStatuses": ["broken", "failed"],
            "messageRegex": ".*bye-bye.*"
        },
        {
            "name": "Outdated tests",
            "matchedStatuses": ["broken"],
            "traceRegex": ".*FileNotFoundException.*"
        },
        {
            "name": "Product defects",
            "matchedStatuses": ["failed"]
        },
        {
            "name": "Test defects",
            "matchedStatuses": ["broken"]
        }
    ]

    allure_cat_file = os.path.join(cm.dir_report_json, 'categories.json')
    with open(allure_cat_file, 'w', encoding='utf-8') as f:
        f.write(str(json.dumps(allure_categories, ensure_ascii=False, indent=4)))
